<?php

if(!defined('DOKU_INC')) die();
require_once(DOKU_PLUGIN.'uniaction/unidb.php');
if(!defined("COURSE_ID")) define("COURSE_ID","course_id");

/**
 * KURSE!
 * Enter description here ...
 */
function showProgramm(){

	//no id? then show list of courses
	if(!isset($_GET[COURSE_ID]))
	return getCourseList();

	//id is given: show special course!
	return getCourse(intval($_GET[COURSE_ID]));
}

/**
 * Vorlesungen!
 * Enter description here ...
 */
function showProgramm2(){

	//no id? then show list of courses
	if(!isset($_GET[COURSE_ID]))
	return getLectureList();

	//id is given: show special course!
	return getLecture(intval($_GET[COURSE_ID]));
}

function showArchive(){
	
	return "TODO: Archiv implementieren, Statistiken anzeigen";
}
/**
 * Kurse und Vorlesungen i did subscribe to
 *
 */
function showMyProgramm(){
	$userId = uni_getUserID();
	if($userId === FALSE) return "<b>Bitte zuerst anmelden um deine Kurse sehen zu können</b>!";

	//get all hoert entries from db for the given userid
	$db = getDBConnection();
	$query = "SELECT * from mykurse where SchuelerID='$userId'";
	$result = doQuery($query);
	if($result === FALSE) trigger_error("Datenbankfehler.",E_WARNING);
	$array = mysql_fetch_assoc($result);
	if($array === FALSE) return "<b>Du hast dich noch zu keinen Veranstaltungen angemeldet!</b>";

	$kurse = array();
	$vorlesungen = array();
	while($array !== false){
		$vorlesung = $array['Vorlesung'];
		unset($array['Vorlesung']);
		unset($array['SchuelerID']);
		if($vorlesung>0){
			unset($array['Bezahlt']);
			unset($array['Gebucht']);
			array_push($vorlesungen,$array);
		}
		else{
			array_push($kurse,$array);
		}
		$array = mysql_fetch_assoc($result);
	}



	//do for kurse
	if(count($kurse) > 0){
		$str.="<h1> Kurse </h1>";
		$str .="<p>Deine Benutzer ID ist <b>$userId</b>. Die Kursnummer ist in der Spalte \"ID\" angeben. Bitte beachte die <a href=\"doku.php?id=information\">Informationen</a> zum Bezahlen deiner gebuchten Kurse und achte besonders auf einen richtigen Verwendungszweck.</p>";

		$str .= getTableHead($kurse[0]);
		for($i = 0;$i < count($kurse);$i++){
			//any modifications
			$kurse[$i]['Veranstaltung'] = "<a href=\"doku.php?id=kurse&course_id=".$kurse[$i]['ID']."\">".$kurse[$i]['Veranstaltung']."</a>";
			if($kurse[$i]['Bezahlt'] == 0) $kurse[$i]['Bezahlt'] = "<b style=\"color:red\">Nein</b>";
			else $array['Bezahlt'] .= " €";
				
			if($kurse[$i]['Gebucht'] == 0) $kurse[$i]['Gebucht'] =  "<b style=\"color:red\">Nein</b>";
			else $kurse[$i]['Gebucht'] = "Ja";
			$str .= getTableContent($kurse[$i]);
		}
		$str .= getTableEnd();
	}

	//do for vorlesungen
	if(count($vorlesungen) > 0){
		$str.="<h1> Vorlesungen </h1>";
		$str .= getTableHead($vorlesungen[0]);
		for($i = 0;$i < count($vorlesungen);$i++){
			//any modifications
			$vorlesungen[$i]['Veranstaltung'] = "<a href=\"doku.php?id=vorlesungen&course_id=".$vorlesungen[$i]['ID']."\">".$vorlesungen[$i]['Veranstaltung']."</a>";
			$str .= getTableContent($vorlesungen[$i]);
		}
		$str .= getTableEnd();
	}


	return $str;
	//display information about
}




function showLogin(){
	$str = "";

	//parse any arguments
	$error = $_SESSION['uni']['login_message'];
	//show loginformular
	if(!isLoggedIn()){
		$str .= showLoginForm($error);

	}
	else {
		$str .= showLoginMenu();
	}

	return $str;
}


function showLoginForm($error = ""){
	$str = "";
	$str = "
	<div class=\"margin_bottom_30\">
    <div class=\"subc links_box_left\">
    
           <h3 class=\"label_small padding_left\">Accountmenu</h3>
<form method=\"post\" action=\"\" accept-charset=\"utf-8\">
<input type=\"hidden\" name=\"id\" value=\"start\" />
<input type=\"hidden\" name=\"uni_action\" value=\"login\" />

          <ul class=\"link_list_arrow_small na_list\">";
	if($error != "")$str .="<li><span style=\"color:red\">$error</span></li>";

	$str .="
           <li><label class=\"block\">Email<input type=\"text\" name=\"uni_email\" class=\"edit\" /></label></li>
           <li><label class=\"block\">Passwort<input type=\"password\" name=\"uni_password\" class=\"edit\" /></label></li>
           <li><input type=\"submit\" value=\"Anmelden\" class=\"button\" /></li>
           <li>Noch keinen Zugang? <a href=\"/doku.php?id=anmeldung\"  class=\"action register\" title=\"Registrieren\">Registrieren</a></li>
          </ul>
</form>
</div></div>";

	return $str;

}

function showLoginMenu(){

	$str = "";
	$str = '
	<div class="margin_bottom_30">
    <div class="subc links_box_left">
       <h3 class="label_small padding_left">Accountmenu</h3>
          <ul class="link_list_arrow_small na_list">
           <li><a href="/doku.php?id=user:my_courses" title="">Meine Kurse</a></li>
           <li><a href="/doku.php?id=user:my_data" title="">Meine Daten</a></li>
           <li><a href="/doku.php?id=user:my_fotos" title="">Fotos aus meinen Kursen</a></li>
           <li><a href="/doku.php?id=start&uni_action=logout" title="">Abmelden</a></li>
          </ul>
    </div>
    </div>
	';



	return $str;


}

function userSubscribedToCourse($id){

	$user_id = uni_getUserID();
	$db = getDBConnection();
	$query = sprintf("SELECT id FROM hoert WHERE sch_id='%s' AND haelt_id='%s'",
	mysql_real_escape_string($user_id),
	mysql_real_escape_string($id));

	$result = doQuery($query);
	if($result === FALSE) trigger_error("Es liegt ein Fehler in der Datenbank vor!", E_USER_WARNING);
	$nr = mysql_affected_rows();
	return ($nr > 0);
}

function getLecture($id){

	//no mysql injection possible
	$id = intval($id);
	$str = "";
	$db = getDBConnection();
	$query = "SELECT * from view_kurs_detail where ID=$id";
	$result = doQuery($query);
	if($result === FALSE) trigger_error("Datenbankfehler.",E_WARNING);
	$array = mysql_fetch_assoc($result);
	if($array === FALSE) return "Es findet keine Veranstaltung mit dieser ID statt.";
	
	foreach($array as $k => $v){
		if($k != 'Url'){
			$array[$k] = htmlentities($v);
		}
	}

	//TODO already subscribed? subscription still possible? status of subscription?
	//show some info if user is logged in
	$subscribeText = "";
	if(isLoggedIn()){
		if(isset($_SESSION['uni']['subscribe_message']) && $_SESSION['uni']['subscribe_message'] != ""){
			$subscribeText = $_SESSION['uni']['subscribe_message'];
		}
		else if(userSubscribedToCourse($array['ID'])){
			$subscribeText = "<a href=\"doku.php?id=vorlesungen&".COURSE_ID."=$id&uni_action=unsubscribe\"><img alt=\"Melde dich für diesen Kurs ab\" src=\"". DOKU_TPL."img/abmelden.png\" /></a>";
		}
		else {
			$subscribeText = "<a href=\"doku.php?id=vorlesungen&".COURSE_ID."=$id&uni_action=subscribe\"><img alt=\"Melde dich jetzt für diesen Kurs an\" src=\"". DOKU_TPL."img/anmelden.png\" /></a>";
		}
	}




	$str .= "<a href=\"doku.php?id=programm\">Zurück zur Programmübersicht.</a>";
	$str .= "<div style='text-align:center'>".$subscribeText."</div>";
	$str .= "<h1>".$array['Titel']."</h1>";
	unset($array['Titel']);
	unset($array['Plaetze']);
	unset($array['Kosten']);
	$array['Art'] = getIsVorlesung($array['Art']);
	if($array['Url'] != ""){
		$array['Url'] = "<a href=\"".$array['Url']."\">".$array['Url']."</a>";
	}
	$str .= print_result_as_table($array);


	return $str;
}


function getCourse($id){

	//no mysql injection possible
	$id = intval($id);
	$str = "";
	$db = getDBConnection();
	$query = "SELECT * from view_kurs_detail where ID=$id";
	$result = doQuery($query);
	if($result === FALSE) trigger_error("Datenbankfehler.",E_WARNING);
	$array = mysql_fetch_assoc($result);
	if($array === FALSE) return "Es findet keine Veranstaltung mit dieser ID statt.";
	

	foreach($array as $k => $v){
		if($k != 'Url'){
			$array[$k] = htmlentities($v);
		}
	}

	//TODO already subscribed? subscription still possible? status of subscription?
	//show some info if user is logged in
	$subscribeText = "";
	if(isLoggedIn()){
		if(isset($_SESSION['uni']['subscribe_message']) && $_SESSION['uni']['subscribe_message'] != ""){
			$subscribeText = $_SESSION['uni']['subscribe_message'];
		}
		else if(userSubscribedToCourse($array['ID'])){
			$subscribeText = "<a href=\"doku.php?id=kurse&".COURSE_ID."=$id&uni_action=unsubscribe\"><img alt=\"Melde dich für diesen Kurs ab\" src=\"". DOKU_TPL."img/abmelden.png\" /></a>";
		}
		else {
			$subscribeText = "<a href=\"doku.php?id=kurse&".COURSE_ID."=$id&uni_action=subscribe\"><img alt=\"Melde dich jetzt für diesen Kurs an\" src=\"". DOKU_TPL."img/anmelden.png\" /></a>";
		}
	}


	$str .= "<a href=\"doku.php?id=programm\">Zurück zur Programmübersicht.</a>";
	$str .= "<div style='text-align:center'>".$subscribeText."</div>";
	$str .= "<h1>".$array['Titel']."</h1>";
	unset($array['Titel']);
	$array['Art'] = getIsVorlesung($array['Art']);
	if($array['Url'] != ""){
		$array['Url'] = "<a href=\"".$array['Url']."\">".$array['Url']."</a>";
	}
	$array['Kosten'] .= " €";
	$str .= print_result_as_table($array);


	return $str;
}

function print_result_as_table($array){
	$str = "";
	$str .= "<table class=\"inline\">";

	foreach ($array as $k => $v){
		$str .= "<tr class=\"row\"><td class=\"col0\">".$k."</td><td class=\"col1\">".$v."</td></tr>\n";
	}

	$str .= "</table>";
	return $str;
}
function tryUniLogin($email,$password){
	$password = hash_password($password,$email);

	$db = getDBConnection();
	$query = sprintf("SELECT id FROM schueler WHERE email='%s' AND password='%s'",
	mysql_real_escape_string($email),
	mysql_real_escape_string($password));

	$result = doQuery($query);
	if($result === FALSE) return "Es existiert ein Problem mit der Datenbank";
	$array = mysql_fetch_assoc($result);
	if($array === FALSE){
		sleep(3);
		return "Falsche Emailadresse / Passwort";
	}
	$_SESSION['uni']['id'] = $array['id'];
}
function getLectureList(){
	$str = "";
	$db = getDBConnection();
	$query = "SELECT * from vorlesungen";
	$result = doQuery($query);
	if($result === FALSE) return "Fehler in der Datenbank.";
	$array = mysql_fetch_assoc($result);
	if($array == false){
		return "Keine Vorlesungen vorhanden! Bitte schauen Sie später wieder vorbei.";
	}
	else{
		$array = editCourseListArray($array,"vorlesungen");
		$str .= getTableHead($array);
		while($array !== false){
			//any modifications
			$str .= getTableContent($array);
			$array = mysql_fetch_assoc($result);
			$array = editCourseListArray($array,"vorlesungen");
		}
		$str .= getTableEnd();

	}
	return $str;
}


function getCourseList(){
	$str = "";
	$db = getDBConnection();
	$query = "SELECT * from kurse";
	$result = doQuery($query);
	if($result === FALSE) return "Fehler in der Datenbank.";
	$array = mysql_fetch_assoc($result);
	if($array == false){
		return "Keine Kurse vorhanden! Bitte schauen Sie sp�ter wieder vorbei.";
	}
	else{
		$array = editCourseListArray($array);
		$str .= getTableHead($array);
		while($array !== false){
			//any modifications
			$str .= getTableContent($array);
			$array = mysql_fetch_assoc($result);
			$array = editCourseListArray($array);
		}
		$str .= getTableEnd();

	}
	return $str;
}
function editCourseListArray($arr,$target = "kurse"){

	$maxTitleLength = 40;

	if($arr === FALSE) return FALSE;
	if(strlen($arr['Veranstaltung']) > $maxTitleLength)$arr['Veranstaltung'] = substr($arr['Veranstaltung'],0,$maxTitleLength)."...";
	$arr['Veranstaltung'] = "<a href='doku.php?id=".$target."&".COURSE_ID."=".intval($arr['ID'])."'>".$arr['Veranstaltung']."</a>";
	return $arr;
}


function getDBConnection(){

	$user = "root";
	$pass = "taketo24";
	$host = "localhost";
	/**
	 $user = "sommer"; // Username f�r Datenbank-Login
	 $pass = "sommer"; // Passwort f�r Datenbank-Login
	 $host = "sommeruni-db.imp.fu-berlin.de:3306"; // Adresse zur Datenbank

	 */
	$db = "sommer"; // Name der Datenbank
	// DB-Connect
	$sql_con = mysql_connect( $host, $user, $pass);
	mysql_select_db($db, $sql_con);
	return $sql_con;
}

function doQuery($query){
	$res = mysql_query($query);
	echo mysql_error();
	return $res;
}

function getTableHead($arr){
	$str = "<table class=\"inline\"><thead><tr>";
	foreach ($arr as $i => $value) {
		$str .= "<th>$i</th>";
	}
	$str .= "</tr></thead><tbody>";
	return $str;
}

function getTableContent($arr){
	$str = "<tr class=\"user_info\">";
	foreach ($arr as $i => $value) {
		$str .= "<td>".utf8_encode($value)."</td>";
	}
	$str .= "</tr>";
	return $str;
}
function getTableEnd(){
	return "</tbody></table>";
}


function hash_password($password, $nonce) {
	$site_key ="dasldcaskfn wekf wer34 prw3 rfakndfqwj3df23orn 23krn23ln123 lel12enl32rn2l3";
	return hash_hmac('md5', $password . $nonce, $site_key);
}

function getIsVorlesung($v){
	if($v == null || $v == 0){
		return "Kurs";
	}
	return "Vorlesung";
}

/**
 * The letter l (lowercase L) and the number 1
 * have been removed, as they can be mistaken
 * for each other.
 */
function createRandomPassword() {

	$chars = "abcdefghijkmnopqrstuvwxyz023456789";
	srand((double)microtime()*1000000);
	$i = 0;
	$pass = '' ;

	while ($i <= 7) {
		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$pass = $pass . $tmp;
		$i++;
	}

	return $pass;

}

function uni_getUserID(){
	if(isset($_SESSION['uni']['id']))
	return $_SESSION['uni']['id'];
	else return FALSE;
}
function isLoggedIn(){
	return isset($_SESSION['uni']['id'] ) && $_SESSION['uni']['id']  != 0;
}

?>